<?php

namespace Home\Model;

use Think\Model;

class OrderModel extends Model {
    function _initialize() {
        parent::_initialize();
        $this->_user_id = session('visitor.user_id');
//        $this->_user_id = 3;
    }
    /**
     *    提交生成订单，外部告诉我要下的单的商品类型及用户填写的表单数据以及商品数据，我生成好订单后返回订单ID
     *
     *    @author    Garbin
     *    @param     array $data
     *    @return    int
     */
    function submit_order($data) {
        /* 释放goods_info和post两个变量 */
        extract($data);
        /* 处理订单基本信息 */
        $base_info = $this->_handle_order_info($goods_info, $post);
        if (!$base_info) {
            /* 基本信息验证不通过 */
            return 0;
        }

        /* 处理订单收货人信息 */
        $consignee_info = $this->_handle_consignee_info($goods_info, $post);
        if (!$consignee_info) {
            /* 收货人信息验证不通过 */
            return 0;
        }

        /* 至此说明订单的信息都是可靠的，可以开始入库了 */

        $base_info['order_amount'] = $base_info['order_amount'];

        /* 插入订单基本信息 */
        //订单总实际总金额，可能还会在此减去折扣等费用
        //优惠后的商品总额
//        $discount = $base_info['goods_amount'] - $base_info['discount'];
//        if ($discount > 0) {
//            $base_info['order_amount'] = $base_info['goods_amount'] + $consignee_info['shipping_fee'] - $base_info['discount'];
//        } else { /* 如果优惠金额大于商品总额 */
//
//            $base_info['order_amount'] = $consignee_info['shipping_fee'];
//            $base_info['discount'] = $base_info['goods_amount'];
//        }


        $order_id = M('Order')->add($base_info);

        if (!$order_id) {
            /* 插入基本信息失败 */
            render('10514', '创建订单失败');
        }

        /* 插入收货人信息 */
        $consignee_info['order_id'] = $order_id;
        M('OrderExtm')->add($consignee_info);

        /* 插入商品信息 */
        $goods_items = array();
        foreach ($goods_info['items'] as $key => $value) {
            $goods_items[] = array(
                'order_id' => $order_id,
                'goods_id' => $value['goods_id'],
                'goods_name' => $value['goods_name'],
                'spec_id' => $value['spec_id'],
                'specification' => $value['specification'],
                'price' => $goods_info['is_discount'] ? $value['discount_price'] : $value['price'],
                'quantity' => $value['quantity'],
                'goods_image' => $value['goods_image'],
//                lichen 2019/5/24 start
                'goods_old_price' => $value['price'],
//                'goods_old_price' => $value['goods_old_price'],
//                'tax_price' => $value['tax_price'],
                'tax_price' => $goods_info['is_discount'] ? $value['tax_discount_price'] : $value['tax_price'],
//                'price_amount' => $goods_info['is_discount'] ? round($value['discount_price'] * $value['quantity'],2) : round($value['price'] * $value['quantity'],2),
                'price_amount' => $goods_info['is_discount'] ? round(($value['discount_price'] - $goods_info['coupon_price'])* $value['quantity'],2) : round(($value['price']-$goods_info['coupon_price']) * $value['quantity'],2),
                'tax_price_amount' => $goods_info['is_discount'] ? round($value['tax_discount_price'] * $value['quantity'],2) : round($value['tax_price'] * $value['quantity'],2),
//                'price_total' => round($value['price'] * $value['quantity'] + $value['tax_price'] * $value['quantity'],2),
//                'price_total' => $goods_info['is_discount'] ? round($value['discount_price'] * $value['quantity'] + $value['tax_discount_price'] * $value['quantity'],2) : round($value['price'] * $value['quantity'] + $value['tax_price'] * $value['quantity'],2),
                'price_total' => $goods_info['is_discount'] ? round(($value['discount_price']- $goods_info['coupon_price']) * $value['quantity'] + $value['tax_discount_price'] * $value['quantity'],2) : round(($value['price'] - $goods_info['coupon_price']) * $value['quantity'] + $value['tax_price'] * $value['quantity'],2),

//                lichen 2019/5/24  end

                'goods_type' => $value['goods_type'] ? $value['goods_type'] : 1,
                'promotions_id' => $value['promotions_id'] ? $value['promotions_id'] : 0,
            );
        }
        M('OrderGoods')->addAll($goods_items); //防止二次注入
        return $order_id;
    }

    /**
     *    处理订单基本信息,返回有效的订单信息数组
     *
     *    @author    Garbin
     *    @param     array $goods_info
     *    @param     array $post
     *    @return    array
     */
    function _handle_order_info($goods_info, $post) {
        /* 默认都是待付款 */
        $order_status = ORDER_PENDING;
        /* 买家信息 */
        $user = M('Member')->where('user_id=' . $this->_user_id)->find();
        /* 返回基本信息 */
        return array(
            'order_sn' => $this->_gen_order_sn(),
            'type' => $goods_info['type'],
            'extension' => 'normal',
            'seller_id' => $goods_info['store_id'],
            'seller_name' => addslashes($goods_info['store_name']),
            'buyer_id' => $this->_user_id,
            'buyer_name' => addslashes($user['user_name']),
            'buyer_email' => $user['email'],
//            lichen 2019/4/12 start
            'buyer_no' => $user['user_no'],
            'phone_mob' => $user['phone_mob'],
//            lichen 2019/4/12 end
            'status' => $order_status,
            'add_time' => time(),
//            lichen 2019/4/12 start
//            'goods_amount' => $goods_info['amount'],
            'goods_amount' => $goods_info['goods_amount'],
            'order_amount' => $goods_info['order_amount'],
//            lichen 2019/4/12 end
            'pd_amount' => isset($post['pd_amount']) ? floatval($post['pd_amount']) : 0.00,
            'discount' => isset($goods_info['discount']) ? $goods_info['discount'] : 0,
            'anonymous' => intval($post['anonymous']),
            'postscript' => trim($post['postscript']),
            'coupon_id' => $goods_info['coupon_id'],
            'commission_amount' => $goods_info['commission_amount'],
            'device' => $goods_info['device']
        );
    }

    /**
     *    处理收货人信息，返回有效的收货人信息
     *
     *    @author    Garbin
     *    @param     array $goods_info
     *    @param     array $post
     *    @return    array
     */
    function _handle_consignee_info($goods_info, $post) {
        /* 验证收货人信息填写是否完整 */
        $consignee_info = $this->_valid_consignee_info($post);
        if (!$consignee_info) {
            return false;
        }
//lichen 2019/5/24 start
//        if (!$goods_info['is_free_fee']) {
//            /* 计算配送费用 */
//            if (empty($goods_info['shipping'][$consignee_info['shipping_id']])) {
//                render('10513', '无此配送方式');
//            }
//            $shipping_info = $goods_info['shipping'][$consignee_info['shipping_id']];
//            $regions_price = $goods_info['shipping'][$consignee_info['shipping_id']]['cod_regions_price'];
//            $suitble_region = 0;
//            if (!empty($regions_price)) {
//                foreach ($regions_price as $key => $region_price) {
//                    if ($consignee_info['region_id'] == $key) {
//                        $region_price_array = explode(",", $region_price);
//                        $shipping_info['step_price'] = floatval($region_price_array[2]);
//                        $shipping_info['first_price'] = floatval($region_price_array[1]);
//                        break;
//                    }
//
//                    $all_regions = array();
//                    $all_regions = array_merge($all_regions, D('Region')->get_descendant($key));
//
//                    if (in_array($consignee_info['region_id'], $all_regions)) {
//                        $region_price_array = explode(",", $region_price);
//
//                        if (($suitble_region == 0) || (count($all_regions) < $suitble_region)) {
//                            $suitble_region = count($all_regions);
//                            $shipping_info['step_price'] = floatval($region_price_array[2]);
//                            $shipping_info['first_price'] = floatval($region_price_array[1]);
//                        }
//                    }
//                }
//            }
//
//            /* 配送费用=首件费用＋超出的件数*续件费用 */
//            $shipping_fee = $shipping_info['first_price'] + ($goods_info['quantity'] - 1) * $shipping_info['step_price'];
//        } else {
            $shipping_fee = 0;
            $consignee_info['shipping_id'] = 0;
            $shipping_info['shipping_name'] = '商家包邮';
//        }
        
        return array(
            'consignee' => $consignee_info['consignee'],
            'region_id' => $consignee_info['region_id'],
            'region_name' => $consignee_info['region_name'],
            'address' => $consignee_info['address'],
            'zipcode' => $consignee_info['zipcode'],
            'phone_mob' => $consignee_info['phone_mob'],
//            lichen 2019/4/12 start
            'user_no' => $consignee_info['user_no'],
//            lichen 2019/4/12 end
            'shipping_id' => $consignee_info['shipping_id'],
            'shipping_name' => addslashes($shipping_info['shipping_name']),
            'shipping_fee' => $shipping_fee,
        );
    }

    /**
     *    验证收货人信息是否合法
     *
     *    @author    Garbin
     *    @param     array $consignee
     *    @return    void
     */
    function _valid_consignee_info($consignee) {
        if (!$consignee['addr_id']) {
            render('10510', '收货地址为空');
        }
//        lichen 2019/5/24 start
//        if (!$consignee['shipping_id'] && !$consignee['is_free_fee']) {
//            render('10512', '配送方式为空');
//        }
//        lichen 2019/5/24 end
        //通过address_id  获取收货信息,存储到订单拓展表
//        $address = M('address')->where('addr_id='.$consignee['addr_id'].' AND user_id='.session('visitor.user_id'))->find();
        $address = M('address')->where('addr_id='.$consignee['addr_id'].' AND user_id='.$this->_user_id)->find();
        if(empty($address)){
            render('19999', '下订单收货地址不存在');
        }
        $consignee['consignee'] = $address['consignee'];
        $consignee['region_id'] = $address['region_id'];
        $consignee['region_name'] = $address['region_name'];
        $consignee['user_no'] = $address['user_no'];
        $consignee['address'] = $address['address'];
        $consignee['zipcode'] = $address['zipcode'];
        $consignee['phone_mob'] = $address['phone_mob'];
        
        return $consignee;
    }

    /**
     *    生成订单号
     *
     *    @author    Garbin
     *    @return    string
     */
    function _gen_order_sn() {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        $timestamp = time();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $orders = M('Order')->where('order_sn=' . $order_sn)->find();
        if (empty($orders)) {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }

        /* 如果有重复的，则重新生成 */
        return $this->_gen_order_sn();
    }

    /**
     *    修改订单中商品的库存，可以是减少也可以是加回
     *
     *    @author    Garbin
     *    @param     string $action     [+:加回， -:减少]
     *    @param     int    $order_id   订单ID
     *    @return    bool
     */
    function change_stock($action, $order_id) {
        if (!in_array($action, array('+', '-'))) {
            render('10516', '错误的库存操作');
        }
        if (!$order_id) {
            render('10001', '缺少参数');
        }

        /* 获取订单商品列表 */
        $order_goods = M('OrderGoods')->where("order_id=" . $order_id)->select();
        if (empty($order_goods)) {
            render('10517', '无订单商品');
        }

        /* 依次改变库存 */
        foreach ($order_goods as $rec_id => $goods) {
            if ($action == '-') {
                M('GoodsSpec')->where('spec_id=' . $goods['spec_id'])->setDec('stock', $goods['quantity']);
            }
            if ($action == '+') {
                M('GoodsSpec')->where('spec_id=' . $goods['spec_id'])->setInc('stock', $goods['quantity']);
            }
        }

        /* 操作成功 */
        return true;
    }

    function submit_order_test($data) {
        /* 释放goods_info和post两个变量 */
        extract($data);
        /* 处理订单基本信息 */
        $base_info = $this->_handle_order_info_test($goods_info, $post);
        if (!$base_info) {
            /* 基本信息验证不通过 */
            return 0;
        }

        /* 处理订单收货人信息 */
        $consignee_info = $this->_handle_consignee_info_test($goods_info, $post);
        if (!$consignee_info) {
            /* 收货人信息验证不通过 */
            return 0;
        }

        /* 至此说明订单的信息都是可靠的，可以开始入库了 */

        /* 插入订单基本信息 */
        //订单总实际总金额，可能还会在此减去折扣等费用
        //优惠后的商品总额
//        $discount = $base_info['goods_amount'] - $base_info['discount'];
//        if ($discount > 0) {
            $base_info['order_amount'] = $base_info['order_amount'];
//        } else { /* 如果优惠金额大于商品总额 */
//
//            $base_info['order_amount'] = $consignee_info['shipping_fee'];
//            $base_info['discount'] = $base_info['goods_amount'];
//        }



        $order_id = M('Order')->add($base_info);

        if (!$order_id) {
            /* 插入基本信息失败 */
            render('10514', '创建订单失败');
        }

        /* 插入收货人信息 */
        $consignee_info['order_id'] = $order_id;
        M('OrderExtm')->add($consignee_info);


        /* 插入商品信息 */
        $goods_items = array();
        foreach ($goods_info['items'] as $key => $value) {
            $goods_items[] = array(
                'order_id' => $order_id,
                'goods_id' => $value['goods_id'],
                'goods_name' => $value['goods_name'],
                'spec_id' => $value['spec_id'],
                'specification' => $value['specification'],
                'price' => $goods_info['is_discount'] ? $value['discount_price'] : $value['price'],
                'quantity' => $value['quantity'],
                'goods_image' => $value['goods_image'],
//                lichen 2019/5/24 start
                'goods_old_price' => $value['price'],
//                'goods_old_price' => $value['goods_old_price'],
                'tax_price' => $value['tax_price'],
                'price_amount' => $goods_info['is_discount'] ? round($value['discount_price'] * $value['quantity'],2) : round($value['price'] * $value['quantity'],2),
                'tax_price_amount' => round($value['tax_price'] * $value['quantity'],2),
//                'price_total' => round($value['price'] * $value['quantity'] + $value['tax_price'] * $value['quantity'],2),
                'price_total' => $goods_info['is_discount'] ? round($value['discount_price'] * $value['quantity'] + $value['tax_price'] * $value['quantity'],2) : round($value['price'] * $value['quantity'] + $value['tax_price'] * $value['quantity'],2),
//                lichen 2019/5/24  end

                'goods_type' => $value['goods_type'] ? $value['goods_type'] : 1,
                'promotions_id' => $value['promotions_id'] ? $value['promotions_id'] : 0,
            );
        }
        M('OrderGoods')->addAll($goods_items); //防止二次注入
        return $order_id;
    }

    function _handle_order_info_test($goods_info, $post) {
        /* 默认都是待付款 */
        $order_status = ORDER_PENDING;
        /* 买家信息 */
        $user = M('Member')->where('user_id=3')->find();
        /* 返回基本信息 */
        return array(
            'order_sn' => $this->_gen_order_sn(),
            'type' => $goods_info['type'],
            'extension' => 'normal',
            'seller_id' => $goods_info['store_id'],
            'seller_name' => addslashes($goods_info['store_name']),
            'buyer_id' => '3',
            'buyer_name' => addslashes($user['user_name']),
            'buyer_email' => $user['email'],
//            lichen 2019/4/12 start
            'buyer_no' => $user['user_no'],
            'phone_mob' => $user['phone_mob'],
//            lichen 2019/4/12 end
            'status' => $order_status,
            'add_time' => time(),
//            lichen 2019/4/12 start
//            'goods_amount' => $goods_info['amount'],
            'goods_amount' => $goods_info['goods_amount'],
            'order_amount' => $goods_info['order_amount'],
//            lichen 2019/4/12 end
            'pd_amount' => isset($post['pd_amount']) ? floatval($post['pd_amount']) : 0.00,
            'discount' => isset($goods_info['discount']) ? $goods_info['discount'] : 0,
            'anonymous' => intval($post['anonymous']),
            'postscript' => trim($post['postscript']),
        );
    }

    function _valid_consignee_info_test($consignee) {
        if (!$consignee['addr_id']) {
            render('10510', '收货地址为空');
        }
//        lichen 2019/5/24 start
//        if (!$consignee['shipping_id'] && !$consignee['is_free_fee']) {
//            render('10512', '配送方式为空');
//        }
//        lichen 2019/5/24 end
        //通过address_id  获取收货信息,存储到订单拓展表
        $address = M('address')->where('addr_id='.$consignee['addr_id'].' AND user_id=3')->find();
        if(empty($address)){
            render('19999', '下订单收货地址不存在');
        }
        $consignee['consignee'] = $address['consignee'];
        $consignee['region_id'] = $address['region_id'];
        $consignee['region_name'] = $address['region_name'];
        $consignee['user_no'] = $address['user_no'];
        $consignee['address'] = $address['address'];
        $consignee['zipcode'] = $address['zipcode'];
        $consignee['phone_mob'] = $address['phone_mob'];

        return $consignee;
    }

    function _handle_consignee_info_test($goods_info, $post) {
        /* 验证收货人信息填写是否完整 */
        $consignee_info = $this->_valid_consignee_info_test($post);
        if (!$consignee_info) {
            return false;
        }
//lichen 2019/5/24 start
//        if (!$goods_info['is_free_fee']) {
//            /* 计算配送费用 */
//            if (empty($goods_info['shipping'][$consignee_info['shipping_id']])) {
//                render('10513', '无此配送方式');
//            }
//            $shipping_info = $goods_info['shipping'][$consignee_info['shipping_id']];
//            $regions_price = $goods_info['shipping'][$consignee_info['shipping_id']]['cod_regions_price'];
//            $suitble_region = 0;
//            if (!empty($regions_price)) {
//                foreach ($regions_price as $key => $region_price) {
//                    if ($consignee_info['region_id'] == $key) {
//                        $region_price_array = explode(",", $region_price);
//                        $shipping_info['step_price'] = floatval($region_price_array[2]);
//                        $shipping_info['first_price'] = floatval($region_price_array[1]);
//                        break;
//                    }
//
//                    $all_regions = array();
//                    $all_regions = array_merge($all_regions, D('Region')->get_descendant($key));
//
//                    if (in_array($consignee_info['region_id'], $all_regions)) {
//                        $region_price_array = explode(",", $region_price);
//
//                        if (($suitble_region == 0) || (count($all_regions) < $suitble_region)) {
//                            $suitble_region = count($all_regions);
//                            $shipping_info['step_price'] = floatval($region_price_array[2]);
//                            $shipping_info['first_price'] = floatval($region_price_array[1]);
//                        }
//                    }
//                }
//            }
//
//            /* 配送费用=首件费用＋超出的件数*续件费用 */
//            $shipping_fee = $shipping_info['first_price'] + ($goods_info['quantity'] - 1) * $shipping_info['step_price'];
//        } else {
        $shipping_fee = 0;
        $consignee_info['shipping_id'] = 0;
        $shipping_info['shipping_name'] = '商家包邮';
//        }


        return array(
            'consignee' => $consignee_info['consignee'],
            'region_id' => $consignee_info['region_id'],
            'region_name' => $consignee_info['region_name'],
            'address' => $consignee_info['address'],
            'zipcode' => $consignee_info['zipcode'],
            'phone_mob' => $consignee_info['phone_mob'],
//            lichen 2019/4/12 start
            'user_no' => $consignee_info['user_no'],
//            lichen 2019/4/12 end
            'shipping_id' => $consignee_info['shipping_id'],
            'shipping_name' => addslashes($shipping_info['shipping_name']),
            'shipping_fee' => $shipping_fee,
        );
    }

}

?>
